package com.fhminyi.GUI;

import com.fhminyi.model.User;
import com.fhminyi.util.DBUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class LoginFrame extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JButton loginButton;
    private JButton registerButton;

    public LoginFrame() {
        setTitle("用户登录");
        setSize(400, 300); // 调整窗口大小
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 测试数据库连接
        testDatabaseConnection();

        // 主面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); // 设置边距
        mainPanel.setBackground(new Color(245, 245, 245)); // 设置背景色

        // Logo 面板
        JPanel logoPanel = new JPanel();
        logoPanel.setBackground(new Color(245, 245, 245));
        JLabel logoLabel = new JLabel("欢迎登录");
        logoLabel.setFont(new Font("微软雅黑", Font.BOLD, 24)); // 设置字体
        logoLabel.setForeground(new Color(0, 102, 204)); // 设置文字颜色
        logoPanel.add(logoLabel);
        mainPanel.add(logoPanel, BorderLayout.NORTH);

        // 输入面板
        JPanel inputPanel = new JPanel(new GridLayout(3, 2, 10, 10));
        inputPanel.setBackground(new Color(245, 245, 245));

        JLabel usernameLabel = new JLabel("用户名:");
        usernameLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        usernameField = new JTextField();
        usernameField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        usernameField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(204, 204, 204)),
                BorderFactory.createEmptyBorder(5, 10, 5, 10)
        ));

        JLabel passwordLabel = new JLabel("密码:");
        passwordLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        passwordField = new JPasswordField();
        passwordField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        passwordField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(204, 204, 204)),
                BorderFactory.createEmptyBorder(5, 10, 5, 10)
        ));

        inputPanel.add(usernameLabel);
        inputPanel.add(usernameField);
        inputPanel.add(passwordLabel);
        inputPanel.add(passwordField);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        buttonPanel.setBackground(new Color(245, 245, 245));

        loginButton = new JButton("登录");
        loginButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        loginButton.setBackground(new Color(0, 102, 204)); // 设置按钮背景色
        loginButton.setForeground(Color.WHITE); // 设置按钮文字颜色
        loginButton.setFocusPainted(false); // 去除焦点边框
        loginButton.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20)); // 设置按钮内边距

        registerButton = new JButton("注册");
        registerButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        registerButton.setBackground(new Color(102, 102, 102)); // 设置按钮背景色
        registerButton.setForeground(Color.WHITE); // 设置按钮文字颜色
        registerButton.setFocusPainted(false); // 去除焦点边框
        registerButton.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20)); // 设置按钮内边距

        buttonPanel.add(loginButton);
        buttonPanel.add(registerButton);

        // 将输入面板和按钮面板添加到主面板
        mainPanel.add(inputPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        // 添加事件监听器
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String username = usernameField.getText();
                String password = new String(passwordField.getPassword());
                if (validateUser(username, password)) {
                    User user = getUserByUsername(username);
                    new WelcomeFrame(user).setVisible(true);
                    dispose(); // 关闭登录窗口
                } else {
                    JOptionPane.showMessageDialog(LoginFrame.this, "用户名或密码错误", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new RegisterFrame().setVisible(true);
            }
        });

        add(mainPanel);
    }

    // 测试数据库连接
    private void testDatabaseConnection() {
        try (Connection conn = DBUtil.getConnection()) {
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库连接错误", "错误", JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }
    }

    // 验证用户
    private boolean validateUser(String username, String password) {
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT * FROM 用户 WHERE 用户名 = ? AND 密码 = ?";
            try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                pstmt.setString(1, username);
                pstmt.setString(2, password);
                try (ResultSet rs = pstmt.executeQuery()) {
                    return rs.next();
                }
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库连接错误", "错误", JOptionPane.ERROR_MESSAGE);
        }
        return false;
    }

    // 根据用户名获取用户信息
    private User getUserByUsername(String username) {
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT * FROM 用户 WHERE 用户名 = ?";
            try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                pstmt.setString(1, username);
                try (ResultSet rs = pstmt.executeQuery()) {
                    if (rs.next()) {
                        User user = new User();
                        user.setUserId(rs.getInt("用户_id"));
                        user.setUsername(rs.getString("用户名"));
                        user.setPassword(rs.getString("密码"));
                        user.setEmail(rs.getString("邮箱"));
                        user.setPhone(rs.getString("电话"));
                        user.setAddress(rs.getString("地址"));
                        user.setRole(rs.getString("角色"));
                        user.setCreateTime(rs.getDate("创建时间"));
                        user.setUpdateTime(rs.getDate("更新时间"));
                        return user;
                    }
                }
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库连接错误", "错误", JOptionPane.ERROR_MESSAGE);
        }
        return null;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new LoginFrame().setVisible(true);
            }
        });
    }
}